package com.haoyeteng.sxbd.modular.business.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.code.kaptcha.Constants;
import com.haoyeteng.sxbd.core.base.controller.BaseController;
import com.haoyeteng.sxbd.core.base.model.ResponseResult;
import com.haoyeteng.sxbd.core.common.annotion.Permission;
import com.haoyeteng.sxbd.core.common.constant.factory.PageFactory;
import com.haoyeteng.sxbd.core.common.exception.BizExceptionEnum;
import com.haoyeteng.sxbd.core.exception.SxbdException;
import com.haoyeteng.sxbd.core.log.LogObjectHolder;
import com.haoyeteng.sxbd.core.shiro.ShiroKit;
import com.haoyeteng.sxbd.core.util.DateUtil;
import com.haoyeteng.sxbd.core.util.KaptchaUtil;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.business.model.User;
import com.haoyeteng.sxbd.modular.business.service.IUserService;
import com.haoyeteng.sxbd.modular.fdc.excel.UsersExcel;
import com.haoyeteng.sxbd.modular.fdc.pojo.Users;
import com.haoyeteng.sxbd.modular.fdc.service.IFDCUserService;
import com.haoyeteng.sxbd.modular.fdc.utils.ExcelUtils;
import com.haoyeteng.sxbd.modular.system.model.Admin;
import com.haoyeteng.sxbd.modular.system.service.IAdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 用户控制器
 *
 * @author haoyeteng
 * @Date 2019-05-17 17:44:46
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	private String PREFIX = "/business/user/";

	@Autowired
	private IUserService userService;
	@Autowired
	private IAdminService adminService;
	@Autowired
	private IFDCUserService fdcUserService;


	/**
	 * 跳转到用户首页
	 */
	@RequestMapping("")
	public String index() {
		return PREFIX + "user.html";
	}

	/**
	 * 跳转到添加用户
	 */
	@RequestMapping("/user_add")
	public String userAdd() {
		return PREFIX + "user_add.html";
	}

	/**
	 * 新增用户
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object add(Users users) {
		fdcUserService.insertUser(users);
		return SUCCESS_TIP;
	}

	/**
	 * 跳转到修改用户
	 */
	@RequestMapping("/user_update/{userId}")
	public String userUpdate(@PathVariable Integer userId, Model model) {
		User user = userService.selectById(userId);
		model.addAttribute("item", user);
		LogObjectHolder.me().set(user);
		return PREFIX + "user_edit.html";
	}

	/**
	 * 获取用户列表
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	// @Permission
	public ResponseResult<Object> list(String status , String name,String phone) {
		ResponseResult<Object> result = new ResponseResult<Object>();
//		Page<User> page = new PageFactory<User>().defaultPage();
		Page<Users> page = new PageFactory<Users>().defaultPage();
		Map<String, Object> params = new HashMap<>(16);
		params.put("status",status);
		params.put("name",name);
		params.put("phone",phone);
//		List<Map<String, Object>> selectUsersList = userService.selectUsersAndAuth(page, authState, userName);
		List<Map<String, Object>> selectUsersList = fdcUserService.selectUsersAndAuth(page,params);
		result.setData(selectUsersList);
		result.setCount(page.getTotal());
		result.setCode(SUCCESS_TIP.getCode());
		result.setMsg(SUCCESS_TIP.getMessage());
		return result;
	}

	/**
	 * 导出本地excel模板
	 */
	@RequestMapping(value = "/downloadExample", method = RequestMethod.POST)
	public void downloadExample(HttpServletResponse response) throws IOException {
		// 获取固定Excel文件作为输入流 (参数为配置的模板路径)
		InputStream in = this.getClass().getResourceAsStream("/statics/admin_users.xls");
		OutputStream toClient = null;
		byte[] buffer;
		try {
			// 获取导出文件的字节数组
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer1 = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer1)) != -1) {
				outStream.write(buffer1, 0, len);
			}
			in.close();
			buffer = outStream.toByteArray();

			// 导出Excel
			if (null != buffer && buffer.length > 0) {
				// 清空response
				response.reset();
				// 设置response的Header
				response.addHeader("Content-Disposition",
						"attachment;filename=" + new String(("导入模板.xlsx").getBytes("GBK"), "ISO8859_1"));
				response.addHeader("Content-Length", "" + buffer.length);
				toClient = response.getOutputStream();
				response.setContentType("application/octet-stream");
				toClient.write(buffer);
				toClient.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(toClient != null){
				toClient.close();
			}
			if(in != null){
				in.close();
			}
		}
	}

	/**
	 * 数据导出
	 */
	@RequestMapping("exportAll")
	public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
		List<Users> usersList = fdcUserService.selectList(new EntityWrapper<Users>());

		ExcelUtils.exportExcelToTarget(response, null, usersList, UsersExcel.class);
	}

	/**
	 * 数据导入
	 */
	@RequestMapping(value = "/importExcelForType", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Object> importExcel(@RequestParam("file") MultipartFile file){
		ResponseResult<Object> result = new ResponseResult<Object>();
		if (!file.isEmpty()) {
			try {
				//获取原始的文件名
				String originalFilename = file.getOriginalFilename();
				//获取文件类型
				String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
				//默认从第一行开始读取
				Integer startRows = 1;
				//获取输入流
				InputStream is = file.getInputStream();
//				List<DoorAntRel> bindingList = new ArrayList<>();
//				List<Bookcase> bookcaseList = new ArrayList<>();
				//Excel导入导出的单元类
				List list=new ArrayList();
				List<String[]> strings = ExcelUtils.readData(fileType, startRows, true, is);
				System.out.println(strings);
				//遍历Excel表每一行的数据
				Users users=new Users();
				for (String[] str : strings) {
					Users users1 = fdcUserService.selectUserByPhone(str[3]);

					if (StringUtils.isEmpty(str[0]) || StringUtils.isEmpty(str[3])){
						list.add(str);
					}
					else if ( fdcUserService.selectUserByPhone(str[3])==null){
						System.out.println(str[0]);
						System.out.println(str[3]);
						users.setCreateTime(new Date());
						users.setName(str[0]);
						users.setPhone(str[3]);
						users.setEmail(str[4]);
						users.setIdent("0");
						users.setIdentType(0);
						if(str[1].equals("禁用")){
							users.setStatus(1);
						}else {
							users.setStatus(0);
						}
						fdcUserService.insert(users);
//						fdcUserService.insertUser(users);
					}else {
						list.add(fdcUserService.selectUserByPhone(str[3]));
					}
				}
				result.setData(list);
				result.setCode(SUCCESS_TIP.getCode());
				result.setMsg(SUCCESS_TIP.getMessage());
				return  result;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		result.setCode(ERROR_TIP.getCode());
//		result.setState(HttpCode.FAILED);
		result.setMsg(ERROR_TIP.getMessage());
		return result;


	}







	/**
	 * 删除用户
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(@RequestParam long id) {
		fdcUserService.deleteById(id);
		return SUCCESS_TIP;
	}

	/**
	 * 跳转到修改用户信息
	 */
	@RequestMapping("/updateUserById/{id}")
	public String updateUserById(@PathVariable long id, Model model) {
		Users users = fdcUserService.selectAndDtlById(id);
		String day=null;
		if (users.getBirth()!=null){
			Date birth = users.getBirth();
			 day = DateUtil.getDay(birth);
		}
		model.addAttribute("item",users);
		model.addAttribute("day",day);
		return PREFIX + "update_user_by_fdc_id.html";
	}


	/**
	 * 修改用户信息
	 */
	@RequestMapping(value = "/updateUsers")
	@ResponseBody
	public Object updateUsers(Users users) {
		fdcUserService.updateUsers(users);
		return SUCCESS_TIP;
	}

	/**
	 * 修改信息
	 */


	/**
	 * 修改密码
	 * 
	 * @param oldPwd
	 * @param newPwd
	 * @param rePwd
	 * @param kaptchas
	 * @return
	 */
	@RequestMapping("/password/update")
	@ResponseBody
	public Object passwordUpdate(@RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd,
			@RequestParam String kaptchas) {
		if (KaptchaUtil.getKaptchaOnOff()) {
			String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
			if (ToolUtil.isEmpty(kaptchas) || !code.equalsIgnoreCase(kaptchas)) {
				throw new SxbdException(BizExceptionEnum.INVALID_KAPTCHA);
			}
		}
		if (!newPwd.equals(rePwd)) {
			throw new SxbdException(BizExceptionEnum.TWO_PWD_NOT_MATCH);
		}
		Integer adminId = ShiroKit.getAdmin().getId();
		Admin admin = adminService.selectById(adminId);
		String oldPwdmd5 = ShiroKit.md5(oldPwd, admin.getSalt());
		if (!oldPwdmd5.equals(admin.getPassword())) {
			throw new SxbdException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
		} else {
			newPwd = ShiroKit.md5(newPwd, admin.getSalt());
			admin.setPassword(newPwd);
			adminService.updateById(admin);
			return SUCCESS_TIP;
		}
	}

	/**
	 * 跳转到基本资料页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/user_update")
	public String userUpdate(Model model) {
		Integer adminId = ShiroKit.getAdmin().getId();
		Admin admin = adminService.selectById(adminId);
		model.addAttribute("admin", admin);
		return PREFIX + "user_update.html";
	}

	/**
	 * 邮箱账号更新
	 */

	@RequestMapping("/update")
	@ResponseBody
	@Permission
	public Object update(@RequestParam String email) {
		Integer id = ShiroKit.getAdmin().getId();
		Admin admin = adminService.selectById(id);
		admin.setEmail(email);
		adminService.updateById(admin);
		return SUCCESS_TIP;
	}

	/**
	 * 用户详情
	 */
	@RequestMapping(value = "/detail/{userId}")
	@ResponseBody
	public Object detail(@PathVariable("userId") Integer userId) {
		return userService.selectById(userId);
	}
}
